﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using socialnetworkApp.Core.JwtService.JwtModel;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;


namespace socialnetworkApp.Core.JwtService
{
    public class AuthenticateService : IAuthenticateService
    {
        public readonly TokenModel _jwtModel;
        public AuthenticateService(IOptions<TokenModel> jwtModel)
        {
            _jwtModel = jwtModel.Value;
        }
        public bool IsAuthenticated(string Username, string PassWordOrValidateCode,string Uid ,out string token)
        {

            token = string.Empty;
            //创建声明Token数组
            var claims = new Claim[] {
                new Claim("Username",Username),
               new Claim("Password",PassWordOrValidateCode),
               new Claim("Uid",Uid),
                new Claim(ClaimTypes.Role, "admin, Manage")
            };
            //密钥 不能给到客户端
            //表示使用对称算法生成的所有密钥的抽象基类。
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtModel.Secret));
            //凭证
            //表示用于生成数字签名的加密密钥和安全算法。
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //生成Token
            var jwtToken = new JwtSecurityToken(_jwtModel.Issuer, _jwtModel.Audience, claims, expires: DateTime.Now.AddMinutes(_jwtModel.AccessExpiration), signingCredentials: credentials);

            token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            return true;
        }
    }
}
